<template>
  <div class="app-container">

    <!-- 表头 查询与新增 -->
    <el-row>
      <el-col :span="24">
        <div class="filter-container">
          <el-input v-model="listQuery.phone" placeholder="手机号码" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter"/>
          <el-select
            v-model="listQuery.createUserId"
            placeholder="发送人"
            clearable
            class="filter-item"
            style="width: 150px"
            @change="handleFilter">
            <el-option v-for="(value, key) in empData" :key="key" :label="value.empName" :value="value.empId"/>
          </el-select>
          <el-select
            v-model="listQuery.status"
            placeholder="有效标志"
            clearable
            class="filter-item"
            style="width: 150px"
            @change="handleFilter">
            <el-option v-for="(value, key) in statusOptions" :key="key" :label="value" :value="key"/>
          </el-select>
          <el-date-picker
            class="filter-item"
            v-model="sendTimeRange"
            type="daterange"
            range-separator="至"
            start-placeholder="发送开始日期"
            end-placeholder="发送结束日期"
            value-format="timestamp">
          </el-date-picker>
          <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
          <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-circle-plus-outline"
                     @click="exportReport">导出
          </el-button>
        </div>
      </el-col>
    </el-row>

    <!-- 表格list -->
    <el-row>
      <el-col :span="24" :gutter="24">
        <el-table
          v-loading="listLoading"
          :key="tableKey"
          :data="list"
          :height="tableHeight"
          element-loading-text="Loading"
          border
          fit
          style="width: 100%;"
          highlight-current-row>
          <el-table-column type="expand">
            <template slot-scope="props">
              <el-form label-position="left" inline class="demo-table-expand">
                <el-form-item label="红包可用产品">
                  <el-transfer v-model="props.row.selectUseGoods" :props="{key: 'pid',label: 'pname'}" :data="productData" disabled="true"/>
                  <span style="color: red">没选为所有产品可用</span>
                </el-form-item>
              </el-form>
            </template>
          </el-table-column>
          <el-table-column align="center" label="序号" width="80">
            <template slot-scope="scope">
              {{ scope.$index }}
            </template>
          </el-table-column>
          <el-table-column label="用户名称" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.userName }}
            </template>
          </el-table-column>
          <el-table-column label="用户手机" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.phone }}
            </template>
          </el-table-column>
          <el-table-column label="使用时间" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.usedTime | timeFilter }}
            </template>
          </el-table-column>
          <el-table-column label="订单号" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.orderId }}
            </template>
          </el-table-column>
          <el-table-column label="过期时间" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.expireTime | timeFilter }}
            </template>
          </el-table-column>
          <el-table-column label="红包名称" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.bonusName }}
            </template>
          </el-table-column>
          <el-table-column label="红包所值金额" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.bonusMoney }}
            </template>
          </el-table-column>
          <el-table-column label="最少金额" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.minGoodsAmount }}
            </template>
          </el-table-column>
          <el-table-column label="红包发送类型" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.sendType | sendTypeFilter }}
            </template>
          </el-table-column>
          <el-table-column label="创建时间" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.createTime | timeFilter }}
            </template>
          </el-table-column>
          <el-table-column label="创建人名称" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.createUserName }}
            </template>
          </el-table-column>
          <el-table-column label="取消人名字" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.recallUserName }}
            </template>
          </el-table-column>
          <el-table-column label="状态" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.status | statusFilter }}
            </template>
          </el-table-column>
          <el-table-column label="描述" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.memo }}
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="180" class-name="small-padding fixed-width">
            <template slot-scope="scope" >
              <el-button v-if="scope.row.status == 1" size="mini" type="primary" @click="handleRecall(scope.row)">
                撤回
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="listQuery.pageNum"
          :limit.sync="listQuery.pageSize"
          layout="total, sizes, prev, pager, next"
          style="float:right;"
          @pagination="fetchData"/>
      </el-col>
    </el-row>

    <!-- 编辑弹窗 -->
    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="right"
        label-width="100px"
        style="">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="红包流水" label-width="105px" prop="id">
              <el-input v-model="temp.id" :disabled="dialogStatus === 'update'"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="红包类型编号" label-width="105px" prop="bonusTypeId">
              <el-input v-model="temp.bonusTypeId"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户编号" label-width="105px" prop="userId">
              <el-input v-model="temp.userId"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="使用时间" label-width="105px" prop="usedTime">
              <el-date-picker
                v-model="temp.usedTime"
                type="date"
                placeholder="选择使用时间"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="订单号" label-width="105px" prop="orderId">
              <el-input v-model="temp.orderId"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="是否被领取" label-width="105px" prop="emailed">
              <el-input v-model="temp.emailed" type="number"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="过期时间" label-width="105px" prop="expireTime">
              <el-date-picker
                v-model="temp.expireTime"
                type="date"
                placeholder="选择过期时间"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="红包名称" label-width="105px" prop="bonusName">
              <el-input v-model="temp.bonusName"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="红包所值金额" label-width="105px" prop="bonusMoney">
              <el-input v-model="temp.bonusMoney"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="红包类型" label-width="105px" prop="bonusType">
              <el-input v-model="temp.bonusType" type="number"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="红包图片" label-width="105px" prop="bonusImg">
              <el-input v-model="temp.bonusImg"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="红包可用产品" label-width="105px" prop="useGoods">
              <el-input v-model="temp.useGoods"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="可以使用该红包的商品的最低价格,即只要达到该价格商品才可以使用红包" label-width="105px" prop="minGoodsAmount">
              <el-input v-model="temp.minGoodsAmount" type="number"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="红包发送类型" label-width="105px" prop="sendType">
              <el-input v-model="temp.sendType" type="number"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="创建时间" label-width="105px" prop="createTime">
              <el-date-picker
                v-model="temp.createTime"
                type="date"
                placeholder="选择创建时间"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="创建人id" label-width="105px" prop="createUserId">
              <el-input v-model="temp.createUserId"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="创建人名称" label-width="105px" prop="createUserName">
              <el-input v-model="temp.createUserName"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="取消人id" label-width="105px" prop="recallUserId">
              <el-input v-model="temp.recallUserId"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="取消人名字" label-width="105px" prop="recallUserName">
              <el-input v-model="temp.recallUserName"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="" label-width="105px" prop="status">
              <el-input v-model="temp.status"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="描述" label-width="105px" prop="memo">
              <el-input v-model="temp.memo"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">确认</el-button>
        <el-button @click="dialogFormVisible = false">取消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import SxBonusRecordApi from '@/api/manage/SxBonusRecordApi'
import SxEmployeeInfoApi from '@/api/manage/SxEmpManageApi'
import SxUserInfoApi from '@/api/manage/SxUserInfoApi'
import sxProductBasicInfoApi from '@/api/manage/SxProductBasicInfoApi'
import waves from '@/directive/waves' // Waves directive
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
export default {
  directives: { waves },
  components: { Pagination },
  filters: {
    sendTypeFilter(sendType) {
      const sendTypeMap = {
        0: '营销人员发送',
        1: '会员级别发送',
        2: '积分兑换',
        3: '分享有礼',
        4: '至美传递'
      }
      if (sendType !== null && sendType !== undefined) {
        return sendTypeMap[sendType]
      }
      return ''
    },
    statusFilter(status) {
      const statusMap = {
        3: '已撤回',
        4: '已经过期',
        2: '已经使用',
        1: '未使用',
        0: '发送失败'
      }
      return statusMap[status]
    },
    validFilter(status) {
      const statusMap = {
        1: '有效',
        0: '作废'
      }
      return statusMap[status]
    },
    timeFilter(time) {
      if (time) {
        return new Date(time).Format('yyyy-MM-dd hh:mm:ss')
      } else {
        return ''
      }
    }
  },
  data() {
    return {
	    tableKey: 0, // 表格key值
      list: null, // 表格对象
      listLoading: true, // 表格加载框
      total: 0, // 分页总数
      tableHeight: window.innerHeight - 220, // 表格高度
      listQuery: { // 表格查询对象
        pageNum: 1,
        pageSize: 10,
        query: '',
        status: null,
        createUserId: null,
        userId: null,
        phone: null,
        id: ''
      },
      temp: {}, // 编辑框临时变量
      statusOptions: {
        3: '已撤回',
        4: '已经过期',
        2: '已经使用',
        1: '未使用',
        0: '发送失败'
      },
      dialogFormVisible: false, // 编辑框显示
      dialogStatus: '', // 编辑框更新插入状态
      textMap: { // 编辑框标题
        update: '编辑',
        create: '创建'
      },
      rules: { // 编辑框校验规则
		   sxBonusRecordName: [{ required: true, message: '名称', trigger: 'change' }]
      },
      productData: [],
      sendTimeRange: [],
      empData: [],
      userData: [],
      exportUrl: process.env.BASE_API + 'sxBonusRecord/export', //下载线下订单
    }
  },
  computed: {
    validSwitch: {
      // getter
      get: function() {
        return this.temp.validFlag === '1'
      },
      // setter
      set: function(newValue) {
        if (newValue) {
          this.temp.validFlag = '1'
        } else {
          this.temp.validFlag = '0'
        }
      }
    },
    queryParam() {
      let param = this.$_.assignIn({}, this.listQuery)
      if (this.sendTimeRange && this.sendTimeRange.length == 2) {
        param.sendStartTime = this.sendTimeRange[0]
        param.sendEndTime = this.sendTimeRange[1]
      }
      return param
    }
  },
  created() {
    this.fetchData()
    this.getRootData()
    this.getUserData()
    this.getEmpData()
  },
  methods: {
    exportReport() {
      // 创建一个 form
      var form1 = document.createElement("form")
      form1.id = "form1"
      form1.name = "form1"

      // 添加到 body 中
      document.body.appendChild(form1)
      // 创建一个输入

      for (const key in this.queryParam) {
        if (this.queryParam[key] != null && this.queryParam[key] != undefined && this.queryParam[key] != '') {
          var input = document.createElement("input")
          input.name = key
          input.value = this.queryParam[key]
          console.log(key + '/' + this.queryParam[key])
          form1.appendChild(input)
        }

      }

      // form 的提交方式
      form1.method = "POST";
      // form 提交路径
      form1.action = this.exportUrl

      // 对该 form 执行提交
      form1.submit()
      // 删除该 form
      document.body.removeChild(form1)

    },
    getUserData() {
      SxUserInfoApi.getList({}).then((data) => {
        this.userData = data
      })
    },
    getEmpData() {
      SxEmployeeInfoApi.getList({}).then(data => {
        this.empData = data
      })
    },
    handleRecall(row) {
      const that = this
      SxBonusRecordApi.recall(row).then((data) => {
        this.$notify({
          title: '成功',
          message: '撤回成功',
          type: 'success',
          duration: 1000,
          onClose() {
            that.fetchData()
          }
        })
      })
    },
    /**
       * 获取顶级结点
       * */
    getRootData() {
      sxProductBasicInfoApi.getRootData({ r: Math.random() }).then((data) => {
        this.productData = data
      })
    },
	  /**
       * 获取表格数据
       */
    fetchData() {
      const that = this
      this.listLoading = true
      this.$http.all([SxBonusRecordApi.getPage(this.queryParam)])
        .then(this.$http.spread(function(perms) {
          that.list = perms.rows
          that.total = perms.total
          that.$_.forEach(that.list, (item) => {
            item.selectUseGoods = JSON.parse(item.useGoods)
            if (item.expireTime < new Date().getTime() && item.status == 1) {
              item.status = 4
            }
          })
          that.listLoading = false
        }))
    },
    /**
       * 新增弹窗
       */
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    /**
       * 清空弹窗内容
       */
    resetTemp() {
      this.temp = {
        id: '',
        bonusTypeId: '',
        userId: '',
        usedTime: '',
        orderId: '',
        emailed: '',
        expireTime: '',
        bonusName: '',
        bonusMoney: '',
        bonusType: '',
        bonusImg: '',
        useGoods: '',
        minGoodsAmount: '',
        sendType: '',
        createTime: '',
        createUserId: '',
        createUserName: '',
        recallUserId: '',
        recallUserName: '',
        status: '',
        memo: '',
        validFlag: '1'
      }
    },
    /**
       * 确定新增
       */
    createData() {
      const that = this
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          SxBonusRecordApi.insert(this.temp).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 1000,
              onClose() {
                that.fetchData()
              }
            })
          })
        }
      })
    },
    /**
       * 编辑弹窗
       */
    handleUpdate(row) {
      this.temp = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    /**
       * 确认编辑
       */
    updateData() {
      const that = this
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          SxBonusRecordApi.update(tempData).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 1000,
              onClose() {
                that.fetchData()
              }
            })
          })
        }
      })
    },
    /**
       * 删除操作
       */
    handleDelete(row) {
      const that = this
      SxBonusRecordApi.remove({ id: row.id }).then(() => {
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 1000,
          onClose() {
            that.fetchData()
          }
        })
      })
    },
    /**
       * 搜索过滤
       */
    handleFilter() {
      this.listQuery.pageNum = 1
      this.fetchData()
    }
  }
}
</script>
